<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="userName" label-width="50px">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNumber">
        <el-input
          v-model="queryParams.idCardNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款账户" prop="accountNumber">
        <el-input
          v-model="queryParams.accountNumber"
          placeholder="请输入收款账户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="打款状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择打款状态" clearable>
          <el-option label="初始化" :value="1" />
          <el-option label="打款中" :value="2" />
          <el-option label="打款完成" :value="3" />
          <el-option label="打款失败" :value="4" />
          <el-option label="打款退回" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="打款类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择打款类型" clearable>
          <el-option label="支付宝" :value="1" />
          <el-option label="银行卡" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="到账时间" prop="payDate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['transfer:payslipDetail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="formData" :rules="rules" ref="tableForm">
      <el-table v-loading="loading" :data="payslipDetailList">
        <el-table-column fixed="left" label="姓名" align="center" prop="userName" min-width="150">
          <template slot-scope="{ row }">
            <el-form-item prop="userName" v-if="row.id === editId">
              <el-input
                v-model="formData.userName"
                placeholder="请输入姓名"
              />
            </el-form-item>
            <span v-else> {{ row.userName }} </span>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" align="center" prop="idCardNumber" min-width="160">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.id === editId" prop="idCardNumber">
              <el-input
                v-model="formData.idCardNumber"
                placeholder="请输入身份证号"
              />
            </el-form-item>
            <span v-else> {{ row.idCardNumber }} </span>
          </template>
        </el-table-column>
        <el-table-column label="打款类型 " align="center" prop="type" min-width="110">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.id === editId" prop="type">
              <el-select v-model="formData.type" placeholder="请选择打款类型">
                <el-option label="支付宝" :value="1"/>
                <el-option label="银行卡" :value="2"/>
              </el-select>
            </el-form-item>
            <template v-else>
              <el-tag type="success" v-if="row.type === 1">支付宝</el-tag>
              <el-tag v-else-if="row.type === 2">银行卡</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="收款账户" align="center" prop="accountNumber" min-width="200">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.id === editId" prop="accountNumber">
              <el-input
                v-model="formData.accountNumber"
                placeholder="请输入收款账户"
                @keyup.enter.native="saveUpdate(row)"
              />
            </el-form-item>
            <span v-else> {{ row.accountNumber }} </span>
          </template>
        </el-table-column>
        <el-table-column label="打款金额" align="center" prop="amount" min-width="150">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.id === editId" prop="amount">
              <el-input-number
                style="width: 100%;"
                v-model="row.amount"
                :min="0.1"
                :controls="false" :precision="2"
                placeholder="请输入打款金额"
              />
            </el-form-item>
            <span v-else> {{ row.amount }}元 </span>
          </template>
        </el-table-column>
        <el-table-column label="服务费" align="center" prop="rateAmount" min-width="150">
          <template slot-scope="{ row }">
            {{ row.rateAmount }}元
          </template>
        </el-table-column>
        <el-table-column label="实际金额" align="center" prop="totalAmount" min-width="150">
          <template slot-scope="{ row }">
            {{ row.totalAmount }}元
          </template>
        </el-table-column>
        <el-table-column label="打款状态 " align="center" prop="status" min-width="110">
          <template slot-scope="{ row }">
            <el-tag type="info" v-if="row.status === 1">初始化</el-tag>
            <el-tag type="warning" v-else-if="row.status === 2">打款中</el-tag>
            <el-tag v-else-if="row.status === 3" type="primary">打款成功</el-tag>
            <el-tag v-else-if="row.status === 5" type="warning">打款退回</el-tag>
            <el-popover
              placement="top-start"
              :width="300"
              trigger="click"
              v-else-if="row.status === 4"
              :content="row.reason"
            >
              <template #reference>
                <el-tag style="cursor: pointer" slot="reference" type="danger">打款失败</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="到账时间" align="center" prop="payDate" width="180"/>
        <el-table-column fixed="right" label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template slot-scope="{ row,$index }">
            <template v-if="row.status === 3">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-more-outline"
                @click="handleReceipt(row)"
              >查看回执单
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listPayslipDetail, updatePayslipDetail, delPayslipDetail } from "@/api/transfer/payslipDetail";

export default {
  name: "PayslipDetail",
  data() {
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入身份证号码'))
      }

      // console.log(value)
      // 检查长度
      if (value.length !== 18) {
        return callback(new Error('身份证号码长度应为18位'));
      }

      // 使用更严格的正则表达式
      const idCardReg = /^\d{17}[\dX]$/;
      if (!idCardReg.test(value)) {
        return callback(new Error('身份证号码格式不正确'));
      }
      // 出生日期验证
      const birthDate = this.extractBirthDate(value)
      if (!birthDate) {
        return callback(new Error('身份证号码校验码错误'))
      }

      // 校验码验证
      if (!this.verifyChecksum(value)) {
        return callback(new Error('身份证号码校验码错误'))
      }

      callback()
    }

    return {
      // 修改ID
      editId: null,
      formData: {},
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发薪人员表格数据
      payslipDetailList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outBatchNo: null,
        outDetailNo: null,
        userName: null,
        idCardNumber: null,
        accountNumber: null,
        type: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '请输姓名', trigger: 'blur' }
        ],
        idCardNumber: [
          { validator: validateIdCard, trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入打款金额', trigger: 'change' }
        ]
      },
      dateRange: []
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    /** 查询发薪人员列表 */
    getList() {
      this.loading = true
      listPayslipDetail(this.addDateRange(this.queryParams, this.dateRange, 'PayDate')).then(response => {
        this.payslipDetailList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 提取出生日期
    extractBirthDate(idCard) {
      try {
        const year = parseInt(idCard.substring(6, 10))
        const month = parseInt(idCard.substring(10, 12)) - 1 // JS Date月份从0开始
        const day = parseInt(idCard.substring(12, 14))

        const date = new Date(year, month, day)

        // 验证日期有效性
        if (
          date.getFullYear() !== year ||
          date.getMonth() !== month ||
          date.getDate() !== day
        ) {
          return null
        }

        return date
      } catch (e) {
        return null
      }
    },

    // 验证校验码
    verifyChecksum(idCard) {
      const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

      let sum = 0
      for (let i = 0; i < 17; i++) {
        sum += parseInt(idCard[i]) * factors[i]
      }

      const mod = sum % 11
      const expectedCode = checkCodes[mod]
      const actualCode = idCard[17].toUpperCase()

      return expectedCode === actualCode
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleUpdate(row) {
      this.formData = { ...row }
      this.editId = row.id
    },
    handleReceipt(row){
      if (row.receiptStatus === 1 || row.receiptStatus === 2){
        this.$message.warning("申请中,请等待")
      }else if (row.receiptStatus === 3){
        window.open( process.env.VUE_APP_BASE_API+row.receiptUrl);
      }
    },

    handleDelete(row){
      this.$modal.confirm('是否确认删除打款姓名为"' + row.userName + '"的数据？').then(()=>{
        return delPayslipDetail(row.id).then(res=>{
          this.$emit("refresh")
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleCancelUpdate(index){
      this.$set(this.payslipDetailList, index,this.formData);
      this.editId = 0
    },

    saveUpdate() {
      this.$refs['tableForm'].validate(valid => {
        if (valid) {
          this.loading = true
          updatePayslipDetail(this.formData).then(response => {
            this.loading = false
            this.editId = 0
            this.getList()
            this.$emit('refresh')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('transfer/payslipDetail/export', {
        ...this.queryParams
      }, `打款人员_${new Date().getTime()}.xlsx`)
    }
  },
};
</script>
